package com.example.mybatis.controller;

import com.example.mybatis.utils.CheckParamUtils;
import com.example.mybatis.dto.UserDTO;
import com.example.mybatis.entity.User;
import com.example.mybatis.common.HttpResult;
import com.example.mybatis.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yh
 * @since 2025-09-29
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    protected UserService userService;

    @Tag(name = "查询用户信息接口")
//     测试查询所有用户
    @Operation(
            summary = "查询所有的用户信息",
            description = "结果按创建时间升序排列"
    )
    @GetMapping
    public HttpResult getAllUsers() {
        try {
            // 查询所有用户
            List<UserDTO> list = userService.list().stream().map(user -> {
                UserDTO dto = new UserDTO();
                org.springframework.beans.BeanUtils.copyProperties(user, dto);
                return dto;
            }).toList();
            return HttpResult.ok(list);
        } catch (IllegalArgumentException e) {
            return HttpResult.error(400, e.getMessage());
        } catch (Exception e) {
            return HttpResult.error(500, "未知错误");
        }
    }
    @Tag(name = "查询用户信息接口",description = "用户信息查询功能")
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询单个用户信息")
    public HttpResult getUserById(@PathVariable("id") Long id) {
        try {
            // 参数校验
            CheckParamUtils.isBiggerZero(id, "用户ID");

            User user = userService.getById(id);
            if (user == null) {
                return HttpResult.error(404, "用户不存在");
            }

            UserDTO dto = new UserDTO();
            org.springframework.beans.BeanUtils.copyProperties(user, dto);
            return HttpResult.ok(dto);
        } catch (IllegalArgumentException e) {
            // 捕获参数校验异常
            return HttpResult.error(400, e.getMessage());
        } catch (Exception e) {
            // 捕获系统异常
            return HttpResult.error(500, "服务器内部错误");
        }
    }




}
